<!-- 附件 -->
<template>
  <div>
    <div style="margin-bottom: 10px" v-if="edit">
      <el-upload ref="uploadRef" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadChange">
        <template #trigger>
          <el-button type="primary" plain>添加附件</el-button>
        </template>
        <!-- <template #tip>
          <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
        </template> -->
      </el-upload>
    </div>
    <div v-loading="loading">
      <ProTable
        ref="proTable"
        :columns="columns"
        :data="list"
        row-key="attrAsName"
        :tool-button="false"
        :pagination="false"
        :height="list.length > 0 ? '' : 200"
      >
        <!-- 操作 -->
        <template #operation="scope">
          <el-button @click="downLoadImg(scope.row)">下载</el-button>
          <!-- <el-button v-if="scope.row.url.includes('20241227/1735299061930.csv')" @click="delFile(scope.row)">删除</el-button> -->
          <el-button @click="delFile(scope.row)">删除</el-button>
        </template>
      </ProTable>
    </div>
  </div>
</template>

<script setup lang="ts" name="EnclosureList">
import { ref, reactive, watch } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";

import ProTable from "@/components/ProTable/index.vue";

import { findAllEventAttachment, uploadAttr, saveEventAttachment } from "@/api/modules/common";
import { findAllAttachment } from "@/api/modules/assetManagement";
import { deleteEventAttachment } from "@/api/modules/eventManagement";
import { deleteAttachement } from "@/api/modules/assetManagement";

import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();

const props = defineProps({
  eno: {
    type: Number
  },
  ciId: {
    type: Number
  },
  eventType: {
    type: String
  },
  edit: {
    type: Boolean,
    default: true
  }
});

const columns = reactive([
  { prop: "attachmentName", label: "名称" },
  { prop: "url", label: "服务器路径" },
  { prop: "operation", label: "操作" }
]);

const list = ref<any[]>([]);

const loading = ref(false);

const getList = () => {
  loading.value = true;
  if (props.eno) {
    // 事件、变更、问题
    findAllEventAttachment({
      "eventAttachmentDto.eno": props.eno,
      "eventAttachmentDto.eventType": props.eventType
    })
      .then((res: any) => {
        list.value = res || [];
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
      });
  } else if (props.ciId) {
    // 资产管理-附件
    findAllAttachment({
      ciId: props.ciId,
      eventType: props.eventType
    })
      .then((res: any) => {
        list.value = res || [];
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
      });
  } else {
    list.value = [];
    loading.value = false;
  }
};

getList();

watch(
  () => props.eno,
  val => {
    getList();
  }
);

watch(
  () => props.ciId,
  val => {
    getList();
  }
);

import type { UploadProps } from "element-plus";
// 上传附件
const uploadChange: UploadProps["onChange"] = (uploadFile: any) => {
  loading.value = true;
  let params = new FormData();
  params.append("filedata", uploadFile.raw);
  uploadAttr("yuehaishuiwu_zhengshi", params)
    .then((res: any) => {
      if (props.eno) {
        // 保存附件（事件、变更、问题）
        saveEventAttachment({
          creator: userStore.username,
          eno: props.eno,
          eventType: props.eventType,
          attachmentStr: res.fileName + "==" + res.msg + "==" + res.fileSize + "-s-"
        })
          .then(() => {
            loading.value = false;
            getList();
          })
          .catch(() => {
            loading.value = false;
          });
      } else if (props.ciId) {
        // 保存附件（资产）
        // todo
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 下载附件
const downLoadImg = item => {
  const a = document.createElement("a");
  a.href = import.meta.env.VITE_API_URL + "/itsm-webapp/pages/attachment!download.action?downloadAttachmentId=" + item.aid;
  a.target = "_blank";
  a.click();
  a.remove();
};

// 删除附件
const delFile = item => {
  ElMessageBox.confirm("确定要删除该附件？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      loading.value = true;
      if (props.ciId) {
        // 资产删除附件
        deleteAttachement(props.ciId, item.aid)
          .then(() => {
            loading.value = false;
            ElMessage.success("删除成功");
            getList();
          })
          .catch(() => {
            loading.value = false;
          });
      } else {
        // 事件删除附件
        deleteEventAttachment({
          eno: item.eno,
          ids: item.aid
        })
          .then(() => {
            loading.value = false;
            ElMessage.success("删除成功");
            getList();
          })
          .catch(() => {
            loading.value = false;
          });
      }
    })
    .catch(() => {
      // cancel operation
    });
};
</script>

<style scoped>
:deep(.card) {
  padding: 0;
  border: none;
}
</style>
